# -*- coding: utf-8 -*-

import sip
sip.setapi('QString', 2)
sip.setapi('QStringList', 2)
sip.setapi('QVariant', 2)

from PyQt4 import QtCore

#_______________________________________________________________________________
class CollectionTreeController(QtCore.QObject):
    def __init__(self, server, model, view):
        QtCore.QObject.__init__(self)
        self.server_ctrl = server
        self.view = view
        self.model = model
        #Signal
        self.model.songs_added_to_playlist.connect(self.add_songs_to_playlist)
#        self.view.header().sectionClicked.connect(self.sort_model)
        self.server_ctrl.client_connected.connect(self.connect)
        self.server_ctrl.database_updated.connect(self.reset)

    def connect(self, connected):
        if connected:
            songs = [item for item in self.server_ctrl.client.listallinfo() 
                     if "directory" not in item]
            self.model.setup_data(songs)
        else:
            self.model.disconnect()
    
    def reset(self):
        self.model.clear()
        songs = [item for item in self.server_ctrl.client.listallinfo() 
                 if "directory" not in item]
        self.model.setup_data(songs)       
  
    def add_songs_to_playlist(self, songs):
        if songs:
            self.server_ctrl.client.command_list_ok_begin()
#            if clear:
#                self.server_ctrl.client.clear()
            for song in songs:
                song = str(song.toUtf8())
                self.server_ctrl.client.addid(song)
            self.server_ctrl.client.command_list_end()